<template>
  <div id="collect">
    <div class="collect_content">
      <h3 class="infoList_title" style="margin:40px 0px 30px 0px">收藏列表</h3>
      <el-button class="createBrief">新建收藏夹</el-button>
      <div class="tableBox">
        <div class="tableBtnGroup">
          <el-button size="mini" icon @click="multiAddDir">加入素材</el-button>
          <el-button size="mini" icon @click="cancelCollectList">取消收藏</el-button>
          <el-button size="mini" icon @click="clearCollectList">清空收藏</el-button>
        </div>

        <el-table
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          v-loading="tableLoading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="35"></el-table-column>
          <el-table-column label="全选本页">
            <template slot-scope="scope">
              <div class="newsBox">
                <h3 class="newsTitle">{{scope.row.title}}</h3>
                <div class="newsContent">{{scope.row.summary}}</div>
                <span class="newsTime">{{scope.row.publishTime}}</span>
                <span class="newsResource">文章来源：{{scope.row.articleRessource}}</span>
                <span class="newsTrigger">触发关键词：{{scope.row.keyword}}</span>
              </div>
              <div class="newsRelevant">
                <span class="rele">相关舆情{{scope.row.total}}条</span>
                <a :href="scope.row.url" target="_blank">查看原文</a>
                <br />
                <span class="newsBtn news_warn" @click="controller(scope.row, 1)">预警</span>
                <span class="newsBtn news_copy" @click="controller(scope.row, 2)">复制文章</span>
                <span class="newsBtn news_collected" @click="cancelCollect(scope.row)">取消收藏</span>
                <!-- <span class="newsBtn news_read">已读</span> -->
                <el-select
                  size="small"
                  width="100px"
                  @change="modifyEmotion(scope.row)"
                  v-model="scope.row.emotionType"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in scope.row.emotionList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          background
          @current-change="handleCurrentChange"
          :current-page="filterData.pageNum"
          :page-size="filterData.pageSize"
          layout="prev, pager, next"
          :total="filterData.total"
        ></el-pagination>
      </div>
    </div>
    <!-- 弹出框 -->
    <copy-props :isVisible.sync="isShowProps" ref="copyRef"></copy-props>
    <sent-alert :isShow.sync="isShowAlert" ref="warnRef" @sendWarnMessage="sendWarnMessage"></sent-alert>
    <collect-prop
      :isShow.sync="isShowCollect"
      ref="collectRef"
      @sendMessage="addCollect"
      @addFolder="addFolder"
    ></collect-prop>
  </div>
</template>
<script>
import "../../assets/css/collect.css";
import $Api from "../../utils/api";
import { formatDate } from "../../utils/common";
import copyProps from "../../components/articleTemplate/copyPorps";
import sentAlert from "../../components/articleTemplate/sentAlert";
import collectProp from "../../components/articleTemplate/collectProp";
export default {
  props: ["folerId"],
  components: {
    copyProps,
    sentAlert,
    collectProp,
  },
  data() {
    return {
      filterData: {
        folerId: this.folerId,
        pageNum: 1, //初始页码
        pageSize: 10, //分页数量
        total: 0, //监测结果总数
      },
      tableData: [],
      statList: [],
      tableLoading: false,
      multipleSelection: [],
      //弹出框组件样式
      isShowProps: false,
      isShowAlert: false,
      isShowCollect: false,
      memberList: [],
      collectList: [],
    };
  },
  watch: {
    folerId() {
      this.$set(this.filterData, "folerId", this.folerId);
      this.initSearchList(1);
    },
  },
  mounted() {
    this.initSearchList(1);
    this.fetchMember();
    this.fetchDirList();
  },
  methods: {
    /**
     * @description: 控制弹窗的显示
     * @param {type} 1预警的显隐 2 复制弹窗的显隐
     */
    controller(data, type) {
      switch (type) {
        case 1: {
          let obj1 = this.$refs["warnRef"].warnList;
          this.$refs["warnRef"].warnList = { ...obj1, ...data };
          this.$refs["warnRef"].objList = this.memberList;
          this.isShowAlert = !this.isShowAlert;
          break;
        }
        case 2: {
          let obj1 = this.$refs["copyRef"].copyData;
          this.$refs["copyRef"].copyData = { ...obj1, ...data };
          this.isShowProps = !this.isShowProps;
          break;
        }
        case 3: {
          this.$refs["collectRef"].collectList.push(data);
          this.$refs["collectRef"].objList = this.collectList;
          this.isShowCollect = !this.isShowCollect;
          break;
        }
      }
    },
    /**
     * @description: 指定页面加载数据
     * @param {Number} i当前加载的页号
     */
    initSearchList(i) {
      this.filterData.pageNum = i;
      this.fetchMyCollectList();
    },
    /**
     * @description: 搜索列表方法
     */
    fetchMyCollectList() {
      let self = this;
      let filterData = this.filterData;
      this.tableLoading = true;
      (async () => {
        try {
          let data = await $Api.fetchMyCollectList(filterData);
          self.tableLoading = false;
          if (data.code == 200) {
            self.$set(self.filterData, "total", data.total);
            data.rows.map((item) => {
              item.emotionList = [
                { value: 0, label: "中立" },
                { value: 1, label: "正面" },
                { value: -1, label: "负面" },
              ];
              return item;
            });
            self.$set(self, "tableData", data.rows);
          }
        } catch {
          self.tableLoading = false;
        }
      })();
    },
    fetchMember() {
      let self = this;
      (async () => {
        let data = await $Api.fetchMember();
        if (data.code == 200) {
          self.$set(self, "memberList", data.data);
        }
      })();
    },
    fetchDirList() {
      let self = this;
      (async () => {
        let data = await $Api.fetchDirList();
        if (data.code == 200) {
          self.$set(self, "collectList", data.data);
          self.$nextTick(() => {
            self.$refs["collectRef"].objList = data.data;
          });
        }
      })();
    },
    /**
     * @description: 发送预警
     * @param {Object} 子组件传过来的预警数据
     */
    sendWarnMessage(data) {
      let self = this;
      (async () => {
        let res = await $Api.sentWarn(data);
        if (res.code == 200) {
          self.isShowAlert = false;
          self.$message.success("预警发送成功");
        }
      })();
    },
    addCollect(data) {
      let self = this;
      (async () => {
        let res = await $Api.addCollect(data);
        if (self.multipleSelection.length) {
          self.$refs.multipleTable.clearSelection();
          self.$refs["collectRef"].collectList = [];
        }
        if (res.code == 200) {
          self.isShowCollect = false;
          self.$message.success("收藏成功");
          self.fetchList();
        }
      })();
    },
    /**
     * @description: 取消收藏
     * @param {type}
     */
    cancelCollect({ id }) {
      let self = this;
      self
        .$confirm("确认取消收藏此文章吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(async () => {
          let res = await $Api.cancelCollect(id);
          if (res.code == 200) {
            self.$message({
              type: "success",
              message: "取消收藏成功!",
            });
            self.initSearchList(1);
          }
        })
    },
    cancelCollectList() {
      let self = this;
      if (self.multipleSelection.length == 0) {
        self.$message.warning("请先选择文章");
        return;
      }
      self
        .$confirm("确认取消收藏这些文章吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(async () => {
          let res = await $Api.cancelCollectList({
            idList: self.multipleSelection.map((item) => item.id),
          });
          if (res.code == 200) {
            self.$message({
              type: "success",
              message: "取消收藏成功!",
            });
            self.$refs.multipleTable.clearSelection();
            self.initSearchList(1);
          }
        });
    },
    clearCollectList() {
      let self = this;
      self
        .$confirm("确认清空收藏文章吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(async () => {
          let res = await $Api.clearCollectList(this.folerId);
          if (res.code == 200) {
            self.$message({
              type: "success",
              message: "清空收藏成功!",
            });
            self.initSearchList(1);
          }
        }) 
    },
    addFolder({ folderName }) {
      let self = this;
      (async () => {
        let res = await $Api.addFolder({ folderName });
        if (res.code == 200) {
          self.$refs["collectRef"].folderName = "";
          self.$message.success("添加收藏夹成功");
          self.fetchDirList();
        }
      })();
    },
    /**
     * @description: 修改情绪
     * @param {Object} 当前文章的参数
     */
    modifyEmotion({ rowKey, publishTime, emotionType }) {
      let self = this;
      (async () => {
        let res = await $Api.modifyEmotion({
          rowKey,
          publishTime,
          emotionType,
        });
        if (res.code == 200) {
          self.$message.success("修改情绪值成功");
          self.fetchList();
        }
      })();
    },
    /**
     * @description: 添加素材库
     */
    multiAddDir() {
      let self = this;
      if (self.multipleSelection.length == 0) {
        self.$message.warning("请先选择素材");
        return;
      }
      (async () => {
        let res = await $Api.multiAddDir(self.multipleSelection);
        if (res.code == 200) {
          self.$message.success("添加素材成功");
          self.$refs.multipleTable.clearSelection();
        }
      })();
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    /**
     * @description: 列表勾选
     * @param {Object} 单个列表项
     */
    handleSelectionChange(val) {
      this.$set(this, "multipleSelection", val);
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.initSearchList(val);
    },
    /**
     * @description: 对时间进行格式化
     * @param {String}  time时间字符串
     * @return {String} 格式化后的时间字符串
     */
    formatDate(time) {
      let date = new Date(time);
      return formatDate(date, "yyyy-MM-dd hh:mm:ss"); //年-月-日 时分
    },
  },
};
</script>
